package com.zhugang.week05;

/**
 * @program algorithms
 * @description: bSearchLastLessThan
 * @author: chanzhugang
 * @create: 2022/07/04 17:45
 */
public class BSearchLastLessThan {

    public static void main(String[] args) {
        BSearchLastLessThan bSearchLastLessThan = new BSearchLastLessThan();
        int[] a = new int[]{2, 3, 4, 4, 4, 7, 9};
        int index = bSearchLastLessThan.bSearchLastLessThan(a, a.length, 8);
        System.out.println(index);
    }

    /**
     * `
     * 查找最后一个小于等于给定值的元素
     *
     * @param a
     * @param n
     * @param target
     * @return
     */
    public int bSearchLastLessThan(int[] a, int n, int target) {
        // 标准二分
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (a[mid] <= target) {
                if (mid == n - 1 || a[mid + 1] > target) {
                    // 向后探测
                    return mid;
                } else {
                    low = mid + 1;
                }
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }

}